<script lang="ts" setup>
  import useTable from '@/hooks/table';
  import { User } from '@/types/user';
  import { onMounted, ref } from 'vue';
  import { getGamePlayerList, createGameUserMatch } from '@/api/game';
  import { Form, Message } from '@arco-design/web-vue';

  const props = defineProps<{
    gameId: string;
  }>();

  const emit = defineEmits(['close']);

  const { list: userList } = useTable<User>();

  const getUserList1 = async (nickname: string) => {
    try {
      const res = await getGamePlayerList({
        pageIndex: 1,
        pageSize: 400,
        gameId: props.gameId,
        nickname,
      });
      userList.value = res?.data?.data?.list || [];
    } finally {
      // do nothing
    }
  };

  const data = ref<{
    userId1?: string;
    userId2?: string;
  }>({});

  const saving = ref(false);
  const formRef = ref<InstanceType<typeof Form> | null>(null);

  const handleSubmit = async () => {
    if (formRef.value) {
      const validate = await formRef.value.validate();
      if (!validate) {
        try {
          saving.value = true;
          await createGameUserMatch(props.gameId, [
            data.value.userId1 as string,
            data.value.userId2 as string,
          ]);
          Message.success('操作成功');
          emit('close', true);
        } finally {
          saving.value = false;
        }
      }
    }
  };

  onMounted(() => {
    getUserList1('');
  });
</script>

<template>
  <a-modal
    title="添加配对球员"
    :width="500"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <a-form ref="formRef" :model="data" layout="vertical">
      <a-form-item
        label="球员1"
        field="userId1"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-select
          v-model="data.userId1"
          allow-search
          :options="
            userList
              .filter((i) => i.userId !== data.userId2)
              .map((i) => ({
                label: `${i.nickname}(证件号码：${i.idNo || '-'}，手机号：${
                  i.phone || '-'
                })`,
                value: i.userId,
              }))
          "
        />
      </a-form-item>

      <a-form-item
        label="球员2"
        field="userId2"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-select
          v-model="data.userId2"
          allow-search
          :options="
            userList
              .filter((i) => i.userId !== data.userId1)
              .map((i) => ({
                label: `${i.nickname}(证件号码：${i.idNo || '-'}，手机号：${
                  i.phone || '-'
                })`,
                value: i.userId,
              }))
          "
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
